import random
from typing import Annotated

from fastapi import Depends, Request

from forward.api.h5.orm.lucky.activity import ActivityORM
from forward.api.h5.orm.lucky.activity_prize import ActivityPrizeORM
from forward.api.h5.orm.lucky.prize_temp import PrizeTempORM
from forward.exceptions.base import AppException
from forward.http_base import HttpResp
from forward.model.schemas.lucky.prize_temp import PrizeTempSchema


class PrizeTempService:
    def __init__(self,
                 request: Request,
                 prize_temp_orm: Annotated[PrizeTempORM, Depends()],
                 activity_orm: Annotated[ActivityORM, Depends()],
                 activity_prize_orm: Annotated[ActivityPrizeORM, Depends()]
                 ):
        self.user_id = request.state.user_id
        self.prize_temp_orm = prize_temp_orm
        self.activit_orm = activity_orm
        self.activity_prize_orm = activity_prize_orm

    async def gen_prize_temp(self, activity_id: int):
        """
        根据活动配置生成奖品
        logic:
        1. 根据活动奖品数量生成奖品
        2. 根据活动奖品数量生成奖品索引
        3. 根据活动奖品索引生成奖品
        4. 返回奖品
        5. 奖品索引和奖品id保存到数据库
        6. 返回奖品索引和奖品id
        """
        # 活动
        activity = await self.activit_orm.get_one_by_id(activity_id)
        if not activity:
            raise AppException(exc=HttpResp.FAILED, msg="活动不存在")

        user_limit_num = activity.client_limit_num
        # 活动关联的奖品
        activity_prize_list = await self.activity_prize_orm.get_all_by_filters(
            activity_id=activity_id
        )
        # 生成用户奖品
        gen_prize_temp_list = []
        for i in range(user_limit_num):

            # 奖池（还有数量的奖品都放进去）随机取出一个作为奖品
            prizes_draw = []
            for item in activity_prize_list:
                if item.num and item.num > 0:
                    prizes_draw.append(
                        PrizeTempSchema(
                            activity_id=activity_id,
                            prize_id=item.prize_id,
                            prize_index=item.prize_index,
                            user_id=self.user_id,
                            status=0
                        ).model_dump()
                    )
            if not prizes_draw:
                raise AppException(exc=HttpResp.FAILED, msg="活动奖品已抽完")
            gen_prize_temp_list.append(random.choice(prizes_draw))

        # 添加用户奖品
        await self.prize_temp_orm.bulk_create(gen_prize_temp_list)

        return True
